package com.java.ratelimter.aop;


import com.java.ratelimter.common.CommonResult;
import com.java.ratelimter.service.BaseLimterService;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 限流切面
 */

@Aspect
@Component
@Log4j2
public class SystemRateAspect {
    @Autowired
    private BaseLimterService baseLimterService;

    @Pointcut("execution(* com..*(..))")
    public  void rateAspect() {
    }

    @Around("rateAspect() && @annotation(limiter)")
    public Object  before(ProceedingJoinPoint joinPoint,RateLimter limiter) throws Exception {
        Boolean bool = baseLimterService.limiter(limiter.rateKey(), limiter.rate());
        if (!bool){
            log.warn("限流了:{}",limiter.rateKey());
            return new CommonResult<>("500","限流了",false);
        }
        try {
            return  joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("限流拦截器异常",throwable);
            return  new CommonResult<>("500",throwable.getMessage(),false);
        }

    }
}
